<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 获取所有模块Service
 * @param string $name 指定service名
 * @return array
 */
function get_all_service($name,$method,$vars=array()){

    if(empty($name))return null;
    $apiPath = APP_PATH.'*/service/'.$name.'.php';
    $apiList = glob($apiPath);
    if(empty($apiList)){
        return;
    }
    $appPathStr = strlen(APP_PATH);
    $method = 'get'.$method.$name;
    $data = array();
    foreach ($apiList as $value) {
        $path = substr($value, $appPathStr,-4);
        $path = str_replace('\\', '/',  $path);
        $appName = explode('/', $path);
        $appName = $appName[0];
        $config = load_config($appName .'/config');
        if(!empty($config['APP_SYSTEM']) &&( !empty($config['APP_STATE']) || !empty($config['APP_INSTALL']))){
            continue;
        }
        $class = model($appName.'/'.$name,'service');
        if(method_exists($class,$method)){
            $data[$appName] = $class->$method($vars);
        }
    }
    return $data;
}
/**
 * 读取模块配置
 * @param string $file 调用文件
 * @return array
 */
function load_config($file){
    $file = get_config_file($file);
    return require $file;
}
/**
 * 解析配置文件路径
 * @param string $file 文件路径或简写路径
 * @return dir
 */
function get_config_file($file){
    $name = $file;
    if(!is_file($file)){
        $str = explode('/', $file);
        $strCount = count($str);
        switch ($strCount) {
            case 1:
                //$app = APP_NAME;
                $app = 'admin';
                $name = $str[0];
                break;
            case 2:
                $app = $str[0];
                $name = $str[1];
                break;
        }
        $app = strtolower($app);
        if(empty($app)&&empty($file)){
            throw new \Exception("Config '{$file}' not found'", 500);
        }
        $file = APP_PATH . "{$app}/conf/{$name}.php";
        if(!file_exists($file)){
            throw new \Exception("Config '{$file}' not found", 500);
        }
    }
    return $file;
}
/**
 * 二维数组排序
 * @param array $array 排序的数组
 * @param string $key 排序主键
 * @param string $type 排序类型 asc|desc
 * @param bool $reset 是否返回原始主键
 * @return array
 */
function array_order($array, $key, $type = 'asc', $reset = false)
{
    if (empty($array) || !is_array($array)) {
        return $array;
    }
    foreach ($array as $k => $v) {
        $keysvalue[$k] = $v[$key];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    $i = 0;
    foreach ($keysvalue as $k => $v) {
        $i++;
        if ($reset) {
            $new_array[$k] = $array[$k];
        } else {
            $new_array[$i] = $array[$k];
        }
    }
    return $new_array;
}

//获取ip
function get_client_ip(){
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return $ip;
}
/**
 * 调用指定模块的API
 * @param string $name  指定api名
 * @return Api
 */
function api($appName,$name,$method,$vars=array()){
    header("Content-type: text/html; charset=utf-8");
    $config = load_config($appName .'/config');
    if(!$config['APP_SYSTEM'] &&( !$config['APP_STATE'] || !$config['APP_INSTALL'])){
        return;
    }
    $class = model($appName.'/'.$name,'api');
    if(method_exists($class,$method)){
        return $class->$method($vars);
    }
}
/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}
/**
 * html代码输入
 */
function html_in($str){
    $str=htmlspecialchars($str);
    if(!get_magic_quotes_gpc()) {
        $str = addslashes($str);
    }
    return $str;
}

/**
 * html代码输出
 */
function html_out($str){
    if(function_exists('htmlspecialchars_decode')){
        $str=htmlspecialchars_decode($str);
    }else{
        $str=html_entity_decode($str);
    }
    $str = stripslashes($str);
    return $str;
}
/**
 * 站点设置信息调取
 */
function get_site($name='site_title'){
    return model('admin/Config')->getInfo()[$name];
}

/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
function delDirAndFile($path, $delDir = FALSE) {
    $handle = opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}

/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名
 */
function convert_arr_key($arr, $key_name){
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}
/**
 * @param $arr
 * @param $key_name
 * @param $key_name2
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
 */
function get_id_val($arr, $key_name,$key_name2)
{
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[$val[$key_name]] = $val[$key_name2];
    }
    return $arr2;
}
//php获取中文字符拼音首字母
function getFirstCharter($str){
    if(empty($str))
    {
        return '';
    }
    $fchar=ord($str{0});
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
    $s1=iconv('UTF-8','gbk',$str);
    $s2=iconv('gbk','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    $asc=ord($s{0})*256+ord($s{1})-65536;
    if($asc>=-20319&&$asc<=-20284) return 'A';
    if($asc>=-20283&&$asc<=-19776) return 'B';
    if($asc>=-19775&&$asc<=-19219) return 'C';
    if($asc>=-19218&&$asc<=-18711) return 'D';
    if($asc>=-18710&&$asc<=-18527) return 'E';
    if($asc>=-18526&&$asc<=-18240) return 'F';
    if($asc>=-18239&&$asc<=-17923) return 'G';
    if($asc>=-17922&&$asc<=-17418) return 'H';
    if($asc>=-17417&&$asc<=-16475) return 'J';
    if($asc>=-16474&&$asc<=-16213) return 'K';
    if($asc>=-16212&&$asc<=-15641) return 'L';
    if($asc>=-15640&&$asc<=-15166) return 'M';
    if($asc>=-15165&&$asc<=-14923) return 'N';
    if($asc>=-14922&&$asc<=-14915) return 'O';
    if($asc>=-14914&&$asc<=-14631) return 'P';
    if($asc>=-14630&&$asc<=-14150) return 'Q';
    if($asc>=-14149&&$asc<=-14091) return 'R';
    if($asc>=-14090&&$asc<=-13319) return 'S';
    if($asc>=-13318&&$asc<=-12839) return 'T';
    if($asc>=-12838&&$asc<=-12557) return 'W';
    if($asc>=-12556&&$asc<=-11848) return 'X';
    if($asc>=-11847&&$asc<=-11056) return 'Y';
    if($asc>=-11055&&$asc<=-10247) return 'Z';
    return null;
}

/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson ($cat_id){
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr'] = model('shop/GoodsCategory')->loadKeyList(array(),'id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = model('shop/GoodsCategory')->loadKeyList(array('parent_id'=>$cat_id),'id,parent_id');
    foreach($son_id_arr as $k => $v){
        getCatGrandson2($k);
    }
    return $GLOBALS['catGrandson'];
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id){
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach($GLOBALS['category_id_arr'] as $k => $v){
        // 找到孙子
        if($v == $cat_id){
            getCatGrandson2($k); // 继续找孙子
        }
    }
}

/**
 * 获取 规格的 笛卡尔积
 * @param $goods_id 商品 id
 * @param $spec_arr 笛卡尔积
 * @return string 返回表格字符串
 */
function getSpecInput($goods_id, $spec_arr){
    // 排序
    if (!empty($spec_arr)){
        foreach ($spec_arr as $k => $v){
            $spec_arr_sort[$k] = count($v);
        }
        asort($spec_arr_sort);
        foreach ($spec_arr_sort as $key =>$val){
            $spec_arr2[$key] = $spec_arr[$key];
        }

        $clo_name = array_keys($spec_arr2);
        $spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积
    }
    $spec = model('Spec')->loadKeyList(array(),'id,name'); // 规格表
    $specItem = model('SpecItem')->loadKeyList(array(),'id,item,spec_id');//规格项
    $keySpecGoodsPrice = model('SpecGoodsPrice')->loadKeyList(array('goods_id'=>$goods_id),'key,key_name,price,store_count,bar_code,sku');//规格项
    $str = "<div class=\"am-u-sm-12\">
            <table width=\"100%\" class=\"am-table am-table-compact am-table-striped tpl-table-black \" id='spec_input_tab'>
            <thead>";
    $str .="<tr>";

    // 显示第一行的数据
    if (!empty($clo_name)){
        foreach ($clo_name as $k => $v){
            $str .=" <td><b>{$spec[$v]}</b></td>";
        }
    }
    $str .="<td><b>价格</b></td>
           <td><b>库存</b></td>
           <td><b>SKU</b></td>
         </tr>
         </thead>
        <tbody>";
    // 显示第二行开始
    if (!empty($spec_arr2)){
        foreach ($spec_arr2 as $k => $v){
            $str .="<tr>";
            $item_key_name = array();
            foreach($v as $k2 => $v2){
                $str .="<td>{$specItem[$v2]['item']}</td>";
                $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
            }
            ksort($item_key_name);
            $item_key = implode('_', array_keys($item_key_name));
            $item_name = implode(' ', $item_key_name);
            if (!empty($keySpecGoodsPrice[$item_key])){
                $str .="<td><input name='item[$item_key][price]' value='{$keySpecGoodsPrice[$item_key]["price"]}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";

                $str .="<td><input name='item[$item_key][store_count]' value='{$keySpecGoodsPrice[$item_key]["store_count"]}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                $str .="<td><input name='item[$item_key][sku]' value='{$keySpecGoodsPrice[$item_key]["sku"]}' />
                <input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";
            }else{
                $str .="<td><input name='item[$item_key][price]' value='0' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
                $str .="<td><input name='item[$item_key][store_count]' value='0' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                $str .="<td><input name='item[$item_key][sku]' value='' />
                <input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";
            }
            $str .="</tr>";
        }
    }
    $str .= "</tbody></table></div>";
    return $str;

}

/**
 * 多个数组的笛卡尔积
 *
 * @param unknown_type $data
 */
function combineDika() {
    $data = func_get_args();
    $data = current($data);
    $cnt = count($data);
    $result = array();
    $arr1 = array_shift($data);
    foreach($arr1 as $key=>$item)
    {
        $result[] = array($item);
    }

    foreach($data as $key=>$item)
    {
        $result = combineArray($result,$item);
    }
    return $result;
}
/**
 * 两个数组的笛卡尔积
 * @param unknown_type $arr1
 * @param unknown_type $arr2
 */
function combineArray($arr1,$arr2) {
    $result = array();
    foreach ($arr1 as $item1)
    {
        foreach ($arr2 as $item2)
        {
            $temp = $item1;
            $temp[] = $item2;
            $result[] = $temp;
        }
    }
    return $result;
}

/**
 * 动态获取商品属性输入框 根据不同的数据返回不同的输入框类型
 * @param int $goods_id 商品id
 * @param int $type_id 商品属性类型id
 */
function getAttrInput($goods_id,$type_id){
    header("Content-type: text/html; charset=utf-8");
    $attributeList = model('GoodsAttribute')->allList(array('type_id'=>$type_id));
    $str='';
    foreach($attributeList as $key => $val){
        $curAttrVal = getGoodsAttrVal(NULL,$goods_id, $val['attr_id']);
        //促使他 循环
        if(count($curAttrVal) == 0)
            $curAttrVal[] = array('goods_attr_id' =>'','goods_id' => '','attr_id' => '','attr_value' => '','attr_price' => '');

        foreach($curAttrVal as $k =>$v){
            $str .= "<div class=\"am-form-group\"><label class='am-u-sm-3 am-form-label attr_{$val['attr_id']}' >";
            $addDelAttr = ''; // 加减符号
            // 单选属性 或者 复选属性
            if($val['attr_type'] == 1 || $val['attr_type'] == 2){
                if($k == 0)
                    $addDelAttr .= "<a onclick='addAttr(this)' href='javascript:void(0);'>[+]</a>&nbsp&nbsp";
                else
                    $addDelAttr .= "<a onclick='delAttr(this)' href='javascript:void(0);'>[-]</a>&nbsp&nbsp";
            }

            $str .= "$addDelAttr {$val['attr_name']}</label><div class=\"am-u-sm-3\">";

            // if($v['goods_attr_id'] > 0) //tp_goods_attr 表id
            //     $str .= "<input type='hidden' name='goods_attr_id[]' value='{$v['goods_attr_id']}'/>";

            // 手工录入
            if($val['attr_input_type'] == 0){
                $str .= "<input type='text' size='40' value='{$v['attr_value']}' name='attr_{$val['attr_id']}[]' />";
            }
            // 从下面的列表中选择（一行代表一个可选值）
            if($val['attr_input_type'] == 1){
                $str .= "<select name='attr_{$val['attr_id']}[]'>";
                $tmp_option_val = explode(PHP_EOL, $val['attr_values']);
                foreach($tmp_option_val as $k2=>$v2){
                    // 编辑的时候 有选中值
                    $v2 = preg_replace("/\s/","",$v2);
                    if($v['attr_value'] == $v2)
                        $str .= "<option selected='selected' value='{$v2}'>{$v2}</option>";
                    else
                        $str .= "<option value='{$v2}'>{$v2}</option>";
                }
                $str .= "</select>";
                //$str .= "属性价格<input type='text' maxlength='10' size='5' value='{$v['attr_price']}' name='attr_price_{$val['attr_id']}[]'>";
            }
            // 多行文本框
            if($val['attr_input_type'] == 2)
            {
                $str .= "<textarea cols='40' rows='3' name='attr_{$val['attr_id']}[]'>{$v['attr_value']}</textarea>";
                //$str .= "属性价格<input type='text' maxlength='10' size='5' value='{$v['attr_price']}' name='attr_price_{$val['attr_id']}[]'>";
            }
            $str .= "</div></div>";
            //$str .= "<br/>";
        }
    }
    return  $str;
}
/**
 * 获取 tp_goods_attr 表中指定 goods_id  指定 attr_id  或者 指定 goods_attr_id 的值 可是字符串 可是数组
 * @param int $goods_attr_id tp_goods_attr表id
 * @param int $goods_id 商品id
 * @param int $attr_id 商品属性id
 * @return array 返回数组
 */
function getGoodsAttrVal($goods_attr_id = 0 ,$goods_id = 0, $attr_id = 0){
    $GoodsAttr = model('GoodsAttr');
    if($goods_attr_id > 0)
        return $GoodsAttr->allList(array('goods_attr_id'=>$goods_attr_id));
    if($goods_id > 0 && $attr_id > 0)
        return $GoodsAttr->allList(array('goods_id'=>$goods_id,'attr_id'=>$attr_id));
}

/**
 * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加
 * @param type $goods_id  商品id
 */
function refresh_stock($goods_id){
    $count = model("SpecGoodsPrice")->where("goods_id = $goods_id")->count();
    if($count == 0) return false; // 没有使用规格方式 没必要更改总库存

    $store_count = model("SpecGoodsPrice")->where("goods_id = $goods_id")->sum('store_count');
    model("Goods")->save(array('store_count'=>$store_count),array('goods_id'=>$goods_id));// 更新商品的总库存
}

/**
 *  获取选中的下拉框
 * @param type $cat_id
 */
function find_parent_cat($cat_id){
    if($cat_id == null)
        return array();
    $cat_list =  model('goods_category')->loadKeyList(array(),'id,parent_id,level');
    $cat_level_arr[$cat_list[$cat_id]['level']] = $cat_id;

    // 找出他老爸
    $parent_id = $cat_list[$cat_id]['parent_id'];
    if($parent_id > 0)
        $cat_level_arr[$cat_list[$parent_id]['level']] = $parent_id;
    // 找出他爷爷
    if (!empty($cat_list[$parent_id]['parent_id'])){
        $grandpa_id = $cat_list[$parent_id]['parent_id'];
    }else{
        $grandpa_id = 0;
    }
    if($grandpa_id > 0)
        $cat_level_arr[$cat_list[$grandpa_id]['level']] = $grandpa_id;

    // 建议最多分 3级, 不要继续往下分太多级
    // 找出他祖父
    if (!empty($cat_list[$grandpa_id]['parent_id'])){
        $grandfather_id = $cat_list[$grandpa_id]['parent_id'];
    }else{
        $grandfather_id = 0;
    }
    if($grandfather_id > 0)
        $cat_level_arr[$cat_list[$grandfather_id]['level']] = $grandfather_id;

    return $cat_level_arr;
}
/**
 * 获取商品规格
 */
function get_spec($goods_id){
    //商品规格 价钱 库存表 找出 所有 规格项id
    $keys = model('shop/SpecGoodsPrice')->loadKeyList(array('goods_id'=>$goods_id),"GROUP_CONCAT(`key` SEPARATOR '_') ")[0];
    $filter_spec = array();
    if ($keys) {
        $where_image['goods_id']=['eq',$goods_id];
        $where_image['src']=['neq',''];
        $specImage = model('shop/SpecImage')->loadKeyList($where_image,"spec_image_id,src");
        $keys = str_replace('_', ',', $keys);
        //$sql = "SELECT a.name,a.order,b.* FROM __PREFIX__spec AS a INNER JOIN __PREFIX__spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY b.id";
        //$filter_spec2 = M()->query($sql);
        $where_spec2['si.id']=['in',($keys)];
        $filter_spec2 = \think\Db::name('spec')
                    ->alias('s')
                    ->field('s.name,s.order,si.*')
                    ->join('spec_item si','s.id = si.spec_id')
                    ->where($where_spec2)
                    ->order('si.id')
                    ->select();
        //model('shop/SpecGoodsPrice')->allList(array('goods_id'=>$goods_id));
        $specGoodsPrice=\think\Db::name('spec_goods_price')
                        ->where(array('goods_id'=>$goods_id))
                        ->column('key,key_name,price');
        foreach ($filter_spec2 as $key => $val) {
            $filter_spec[$val['name']][] = array(
                'item_id' => $val['id'],
                'item' => $val['item'],
                'src' => $specImage[$val['id']],
                'price'=>$specGoodsPrice[$val['id']]['price']
            );
        }
    }
    return $filter_spec;
}

/**
 * 订单确认收货
 * @param $id   订单id
 */
function confirm_order($id,$user_id = 0){

    $where = "order_id = $id";
    $user_id && $where .= " and user_id = $user_id ";
    $order = \think\Db::name('order')->where($where)->find();
    if($order['order_status'] != 1)
        return array('status'=>-1,'msg'=>'该订单不能收货确认');

    $data['order_status'] = 2; // 已收货
    $data['pay_status'] = 1; // 已付款
    $data['confirm_time'] = time(); // 收货确认时间
    if($order['pay_code'] == 'cod'){
        $data['pay_time'] = time();
    }
    $row = \think\Db::name('order')->where(array('order_id'=>$id))->update($data);
    if(!$row)
        return array('status'=>-3,'msg'=>'操作失败');
    return array('status'=>1,'msg'=>'操作成功');
}
/**
 * 支付完成修改订单
 * $order_sn 订单号
 * $pay_status 默认1 为已支付
 */
function update_pay_status($order_sn,$pay_status = 1){
    $where_count['order_sn']=['eq',$order_sn];
    $where_count['pay_status']=['eq','0'];
    if(stripos($order_sn,'recharge') !== false){
        //用户在线充值
        $count = \think\Db::name('recharge')->where($where_count)->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        if($count == 0) return false;
        $order = \think\Db::name('recharge')->where('order_sn',$order_sn)->find();
        \think\Db::name('recharge')->where('order_sn',$order_sn)->update(array('pay_status'=>1,'pay_time'=>time()));
        accountLog($order['user_id'],$order['account'],0,'会员在线充值');
    }else{
        // 如果这笔订单已经处理过了
        $count = model('order')->where($where_count)->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        if($count == 0) return false;
        // 找出对应的订单
        $order = model('order')->where('order_sn',$order_sn)->find();
        // 修改支付状态  已支付
        $order_data['pay_status']=1;
        $order_data['pay_time']=time();
        \think\Db::name('order')->where('order_sn',$order_sn)->update($order_data);
        // 减少对应商品的库存(暂不处理)
        //minus_stock($order['order_id']);
        // 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额(暂不处理)
        //update_user_level($order['user_id']);
        // 记录订单操作日志
        logOrder($order['order_id'],'订单付款成功','付款成功',$order['user_id']);
        //分销设置(暂不处理)
        //model('rebate_log')->where("order_id = {$order['order_id']}")->save(array('status'=>1));
        // 成为分销商条件(暂不处理)
        //$distribut_condition = tpCache('distribut.condition');
        //if($distribut_condition == 1)  // 购买商品付款才可以成为分销商(暂不处理)
        //model('users')->where("user_id = {$order['user_id']}")->save(array('is_distribut'=>1));
    }
}
/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id  订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id  用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id,$action_note,$status_desc,$user_id = 0){
    $status_desc_arr = array('提交订单', '付款成功', '取消', '等待收货', '完成','退货');
    // if(!in_array($status_desc, $status_desc_arr))
    // return false;
    $order = \think\Db::name('order')->where('order_id',$order_id)->find();
    $action_info = array(
        'order_id'        =>$order_id,
        'action_user'     =>$user_id,
        'order_status'    =>$order['order_status'],
        'shipping_status' =>$order['shipping_status'],
        'pay_status'      =>$order['pay_status'],
        'action_note'     => $action_note,
        'status_desc'     =>$status_desc, //''
        'log_time'        =>time(),
    );
    return \think\Db::name('order_action')->insert($action_info);
}

/**
 * 根据规格id获取规格名称
 */
function get_spec_item_name($item_id){
    if (empty($item_id)){
        return '';
    }
    $info=\think\Db::name('spec_item')->where('id',$item_id)->find();
    if (empty($info)){
        return '';
    }
    return $info['item'];
}

//根据用户id获取该用户购买的商品数量
function get_user_spec_num($user_id=null,$brand_id=null){
    $where=array();
    if ($user_id!==null){
        $where['o.user_id']=$user_id;
    }
    if ($brand_id!==null){
        $where['og.brand_id']=$brand_id;
    }
    $order_goods_list=\think\Db::name('order_goods')
                ->alias('og')
                ->field('og.spec_json')
                ->join('order o','og.order_id=o.order_id','left')
                ->where($where)
                ->select();
    $num=0;
    if ($order_goods_list){
        foreach ($order_goods_list as $key=>$val){
            $spec_json=json_decode($val['spec_json'],true);
            if ($spec_json){
                foreach ($spec_json as $vo){
                    foreach ($vo as $k=>$v){
                        $num+=$v['num'];
                    }
                }
            }
        }
    }
    return $num;
}
/**
 * 根据品牌id查找该品牌下有多少件商品
 */
function get_brand_goods_num($brand_id){
    if (empty($brand_id)){
        return ;
    }
    $count=\think\Db::name('goods')->where('brand_id',$brand_id)->count();
    return $count;
}

/**
 * @param $user_id 用户id
 * @param $money 定金金额
 * @return array|void 
 */
function get_user_discount($user_id,$money){
    if (empty($user_id)){
        return ;
    }
    $user_info=\think\Db::name('user')->where('user_id',$user_id)->find();
    if (empty($user_info)){
        return ;
    }
    $discount_info=array();
    if ($user_info['level']==1){
        $prom_order=\think\Db::name('prom_order')->where('id',1)->find();
        if ($money>=$prom_order['money']){
            $discount_info['discount']=$prom_order['expression']/100;
            $discount_info['info']='注册会员订单满'.$prom_order['money'].'元'.$discount_info['discount'].'折扣';
            return $discount_info;
        }else{
            $discount_info['discount']=100/100;
            $discount_info['info']='注册会员订单未满'.$prom_order['money'].'元'.'没有折扣';
            return $discount_info;
        }
    }else{
        $level_discount=\think\Db::name('user_level')->where('level_id',$user_info['level'])->find();
        $discount_info['discount']=$level_discount['discount']/100;
        $discount_info['info']=$level_discount['level_name'].$discount_info['discount'].'折扣';
        return $discount_info;
    }
}

/**
 * 根据用户user_id获取用户表字段信息
 * @param $user_id 用户id
 * @param $field 用户表字段
 * @return mixed|void 返回用户表字段信息
 */
function get_username($user_id,$field){
    if (empty($user_id)){
        return ;
    }
    $user_info=\think\Db::name('user')->where('user_id',$user_id)->find();
    if ($user_info){
        return $user_info[$field];
    }else{
        return ;
    }
}

/**
 * 将二维数组以元素的某个值作为键 并归类数组
 * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
 * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
 * @param $arr 数组
 * @param $key 分组值的key
 * @return array
 */
function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}
/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array){
    if(!is_array($array))
        return trim($array);
    return array_map('trim_array_element',$array);
}

/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str){
    $data = array();
    $parameter = explode('&',end(explode('?',$str)));
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}
/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id,$width,$height){
    if(empty($goods_id))
        return '';
    //判断缩略图是否存在
    $path = "uploads/goods/thumb/$goods_id/";

    $goods_thumb_name ="goods_thumb_{$goods_id}_{$width}_{$height}";

    // 这个商品 已经生成过这个比例的图片就直接返回了
    if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg';
    if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg';
    if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif';
    if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png';
    //$original_img = model('Goods')->where("goods_id = $goods_id")->getField('original_img');
    $original_img = \think\Db::name('goods')->field('original_img')->where('goods_id',$goods_id)->find()['original_img'];

    if(empty($original_img)) return '';

    $original_img = '.'.$original_img; // 相对路径
    if(!file_exists($original_img)) return '';


    $image = \think\Image::open($original_img);
    //生成缩略图
    if(!is_dir($path)){
        mkdir($path,0777,true);
    }
    $goods_thumb_name = $goods_thumb_name. '.'.$image->type();
    $image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100);
    //图片水印处理
    /*$water = tpCache('water');
    if($water['is_mark']==1){
        $imgresource = './'.$path.$goods_thumb_name;
        if($width>$water['mark_width'] && $height>$water['mark_height']){
            if($water['mark_type'] == 'img'){
                $image->open($imgresource)->water(".".$water['mark_img'],$water['sel'],$water['mark_degree'])->save($imgresource);
            }else{
                //检查字体文件是否存在
                if(file_exists('./zhjt.ttf')){
                    $image->open($imgresource)->text($water['mark_txt'],'./zhjt.ttf',20,'#000000',$water['sel'])->save($imgresource);
                }
            }
        }
    }*/
    return '/'.$path.$goods_thumb_name;
}